package model.daos;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import model.db.DataBase;
import model.dtos.Umpire;

public class UmpireDao implements GenericDao<Umpire>
{

	@Override
	public void save(Umpire dt)
	{
		DataBase.getSeason().getUmpires().add(dt);
	}

	@Override
	public Umpire findById(String id)
	{
		Umpire umpire = null;
		
		for (Umpire u : DataBase.getSeason().getUmpires())
		{
			if (u.getIdentification().equals(id))
			{
				umpire = u;
				break;
			}
		}
		
		return umpire;
	}

	@Override
	public List<Umpire> findAll()
	{
		return DataBase.getSeason().getUmpires();
	}

	@Override
	public void deleteById(String id)
	{
		Iterator<Umpire> it = DataBase.getSeason().getUmpires().iterator();
		
		while (it.hasNext())
		{
			if (it.next().getIdentification().equals(id))
			{
				it.remove();
				break;
			}
		}
	}

	@Override
	public void deleteAll()
	{
		DataBase.getSeason().getUmpires().clear();
	}
	
	public void loadUmpiresFromFile(File file) throws IOException, ParseException
	{
		BufferedReader bf = new BufferedReader(new FileReader(file));
		
		String line = null;
		while ((line = bf.readLine()) != null)
		{
			StringTokenizer tok = new StringTokenizer(line, ";");
			DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
						
			DataBase.getSeason().getUmpires().add(new Umpire(tok.nextToken(), tok.nextToken(), tok.nextToken(), df.parse(tok.nextToken())));
		}
		
	}
}
